const sizeMap: Record<string, number> = {
  b: 1,
  kb: 1 << 10,
  mb: 1 << 20,
  gb: 1 << 30,
  tb: Math.pow(1024, 4),
  pb: Math.pow(1024, 5)
};

const formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g;

const formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/;

/**
 * Format the given value in bytes into a string.
 *
 * If the value is negative, it is kept as such. If it is a float,
 * it is rounded.
 *
 * @param {number} value
 * @param {object} [options]
 * @param {number} [options.decimalPlaces=2]
 * @param {number} [options.fixedDecimals=false]
 * @param {string} [options.thousandsSeparator=]
 * @param {string} [options.unit=]
 * @param {string} [options.unitSeparator=]
 *
 * @returns {string|null}
 * @public
 */

export function formatFileSize(
  value: number,
  options?: {
    decimalPlaces?: number;
    fixedDecimals?: boolean;
    thousandsSeparator?: string;
    unit?: string;
    unitSeparator?: string;
  }
): string | number {
  if (!Number.isFinite(value)) return value;

  const mag = Math.abs(value);
  const thousandsSeparator = (options && options?.thousandsSeparator) || '';
  const unitSeparator = (options && options?.unitSeparator) || '';
  const decimalPlaces =
    options && options?.decimalPlaces !== undefined
      ? options?.decimalPlaces
      : 2;
  const fixedDecimals = Boolean(options && options?.fixedDecimals);
  let unit = (options && options?.unit) || '';

  if (!unit || !sizeMap[unit.toLowerCase()]) {
    if (mag >= sizeMap.pb) {
      unit = 'PB';
    } else if (mag >= sizeMap.tb) {
      unit = 'TB';
    } else if (mag >= sizeMap.gb) {
      unit = 'GB';
    } else if (mag >= sizeMap.mb) {
      unit = 'MB';
    } else if (mag >= sizeMap.kb) {
      unit = 'KB';
    } else {
      unit = 'B';
    }
  }

  const val = value / sizeMap[unit.toLowerCase()];
  let str = val.toFixed(decimalPlaces);

  if (!fixedDecimals) {
    str = str.replace(formatDecimalsRegExp, '$1');
  }

  if (thousandsSeparator) {
    str = str
      .split('.')
      .map(function (s, i) {
        return i === 0
          ? s.replace(formatThousandsRegExp, thousandsSeparator)
          : s;
      })
      .join('.');
  }

  return str + unitSeparator + unit;
}
